package edu.whu.demo.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.whu.demo.domain.Operation;
import edu.whu.demo.service.impl.OperationServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2022-11-24
 */
@RestController
@RequestMapping("/operation")
public class OperationController {

    @Autowired
    OperationServiceImpl operationService;

    @ApiOperation("查找管理员操作记录")
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('admin')")
    public IPage<Operation> findOperation(@PathVariable Long id,
                                            @RequestParam Integer pageNum,
                                            @RequestParam Integer pageSize,
                                            @RequestParam(required=false) String type,
                                            @RequestParam(required=false) String beginTime,
                                            @RequestParam(required=false) String endTime,
                                            @RequestParam(required=false) Boolean order){
        Map<String,Object> condition = new HashMap<>();
        condition.put("admin_id",id);
        if(type != null){
            condition.put("type",type);
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if(beginTime != null && !beginTime.equals("")){
            LocalDateTime start = LocalDateTime.parse(beginTime, fmt);
            condition.put("beginTime",start);
        }
        if(endTime != null && !endTime.equals("")){
            LocalDateTime end = LocalDateTime.parse(endTime, fmt);
            condition.put("endTime",end);
        }
        if(order != null){
            condition.put("order",order);
        }
        return operationService.findOperation(id,condition,pageNum,pageSize);
    }

    @ApiOperation("添加管理员操作记录")
    @PostMapping("")
    @PreAuthorize("hasRole('admin')")
    public Operation addOperation(@RequestBody Operation operation){
        return operationService.addOperation(operation);
    }

}

